package com.tianyuan.lims.common.config;

import com.jfinal.handler.Handler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CorsHandler extends Handler {

    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        // 允许所有来源（生产环境建议指定具体域名，如 "https://example.com"）
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许的请求方法
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        // 允许的请求头
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        // 允许客户端携带Cookie（如果需要跨域传递Cookie，此处设为true，且Access-Control-Allow-Origin不能为*）
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 预检请求的有效期（秒），避免频繁预检
        response.setHeader("Access-Control-Max-Age", "3600");

        // 处理 OPTIONS 预检请求（直接返回200，无需后续处理）
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            isHandled[0] = true; // 标记为已处理，终止后续Handler链
            return;
        }

        // 继续执行后续处理器
        next.handle(target, request, response, isHandled);
    }
}
